package cn.edu.bit.lixin.blog.util;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.util.Random;

public class VerifyCodeUtil {
	private static final int IMAGE_WIDTH = 68;
	private static final int IMAGE_HEIGHT = 22;
	private static final char[] ch = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".toCharArray();
	
	//根据传入的字符生成验证码的图片
	public static BufferedImage generateVerifyImage(String verifyCode){
		BufferedImage image = new BufferedImage(IMAGE_WIDTH, IMAGE_HEIGHT, BufferedImage.TYPE_INT_RGB);
		
		//得到该图片的绘图对象
		Graphics g = image.getGraphics();
		Color c = new Color(200, 150, 255);
		g.setColor(c);
		//填充整个图片的颜色
		g.fill3DRect(0, 0, IMAGE_WIDTH, IMAGE_HEIGHT, true);
        
		Random r = new Random();
        int index, len = ch.length;
        for (int i = 0;i < 4; i++){
        	g.setColor(new Color(r.nextInt(88), r.nextInt(188), r.nextInt(255)));
        	g.setFont(new Font("Arial", Font.BOLD | Font.ITALIC, 22));// 输出的字体和大小  
        	g.drawString("" + verifyCode.charAt(i), (i * 15) + 3, 18);//写什么数字，在图片的什么位置画
        }
        
        return image;
	}
	
	//生成验证码上的字符
	public static String generateVerifyCode(){
		Random r = new Random();
		int index,len = ch.length;
		StringBuffer sb = new StringBuffer();
		for (int i = 0;i < 4;i++){
			index = r.nextInt(len);
			sb.append(ch[index]);
		}
		return sb.toString();
	}
}
